package fem2.gui.actions;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;

import fem2.Model;
import fem2.gui.Viewer;

public class SaveModelAction extends AbstractAction {

	private static final long serialVersionUID = 1L;

	// Class TypeOfFile
	public static class FileType extends FileFilter {
		// Type of file that should be display in JFileChooser will be set here
		// We choose to display only directory and text file
		public boolean accept(File f) {
			return f.isDirectory() || f.getName().toLowerCase().endsWith(".model");
		}

		// Set description for the type of file that should be display
		public String getDescription() {
			// return "model serialization files";
			return ".model";
		}
	}

	public SaveModelAction() {
		super("Save Model");
		putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl M"));
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		Viewer v = (Viewer) Frame.getFrames()[0];
		Model m = v.getModel().getModel();
		try {
			String wd = System.getProperty("user.dir");
			JFileChooser fc = new JFileChooser(wd);
			fc.setFileFilter(new FileType());
			int rc = fc.showDialog(null, "Select Save File");
			if (rc == JFileChooser.APPROVE_OPTION) {
				File file = fc.getSelectedFile();
				String filename = file.getAbsolutePath();
				m.Save(filename);
			}
		} catch (FileNotFoundException e) {
			throw new Error("File not found");
		} catch (IOException e) {
			throw new Error("Write model failed");
		}
	}

}
